package com.example.administrator.ygddriver.welcome;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.administrator.ygddriver.R;
import com.example.administrator.ygddriver.base.BaseActivity;
import com.example.administrator.ygddriver.tool.OkGoRequests;
import com.example.administrator.ygddriver.tool.UrlValuse;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.io.ByteArrayOutputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;


public class PayActivity extends BaseActivity {
    private TextView mTimeTv;
    //    private CountDownTimer timer;
    private String token;
    private Boolean tag = true;
    private Boolean complete = false;
    private Button button;
    private String ip;

    @Override
    public int initLayout() {
        return R.layout.actvity_pay;
    }

    @Override
    public void initView() {
//        mTimeTv = findViewById(R.id.activity_welcome_time_tv);
        button = findViewById(R.id.activity_pay);
    }

    @Override
    public void initDate() {
//        WXWebpageObject wxWebpageObject = new WXWebpageObject();
//        wxWebpageObject.webpageUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe939ed063ca0a500&redirect_uri=http%3a%2f%2fwww.yigongdao.cn%2fwx%2fshare%2finvitation&response_type=code&scope=snsapi_userinfo&state={key:hhh,kuu:jjj}#wechat_redirect";
//        WXMediaMessage mediaMessage = new WXMediaMessage(wxWebpageObject);
//        mediaMessage.title = "易工到";
//        mediaMessage.description = "易工到首页";
//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.logo_2);
//        mediaMessage.thumbData = bmpToByteArray(bitmap, true);
//        final SendMessageToWX.Req req = new SendMessageToWX.Req();
//        req.transaction = buildTransaction("xx");
//        req.message = mediaMessage;
//        req.scene = WXSceneSession;

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                IWXAPI api = WXAPIFactory.createWXAPI(WelcomeActivity.this, null);
//                api.registerApp("wxed61e43845c60a4d");
//                SendAuth.Req req = new SendAuth.Req();
//                req.scope = "snsapi_userinfo";
//                api.sendReq(req);

//                OkGo.<String>post("http://192.168.1.140:8200/api/pay/refund").params("out_trade_no","423cf21628f14d0bb2a8e2bbffa6405e").params("total_fee","0.01").params("refund_fee","0.01").execute(new StringCallback() {
//                    @Override
//                    public void onSuccess(Response<String> response) {
//
//                    }
//                });


//
//                IWXAPI iwxapi;
//                iwxapi = WXAPIFactory.createWXAPI(WelcomeActivity.this, null); //初始化微信api
//                iwxapi.registerApp("wxed61e43845c60a4d"); //注册appid  appid可以在开发平台获取
//                SendAuth.Req req = new SendAuth.Req();
//                req.scope = "snsapi_userinfo";
//                req.state = "wechat_sdk_demo_test";
//                iwxapi.sendReq(req);

                HashMap<String, String> h = new HashMap<>();
                h.put("total_fee", "1");
                h.put("spbill_create_ip", ip);
                h.put("body", "易工到测试直接转账");
                h.put("c_waybill", null);
                h.put("c_customer", null);
                h.put("c_driver", null);
                h.put("c_apitype", "1");
                h.put("c_paytype", "3");
                h.put("c_relation", null);
                h.put("c_freight", "1");
                h.put("c_change", null);
                h.put("c_token", null);
                h.put("c_type", UrlValuse.TYPE);
                h.put("appid", UrlValuse.WXAPP_ID);
                OkGoRequests.getInstance().putRequestAsync("http://www.yigongdao.cn/wx/pay/createOrder", h, WXBean.class, new OkGoRequests.OnTrue<WXBean>() {
                    @Override
                    public void hasData(WXBean date) {
                        Log.d("111111", date.getResult().getWxPayAppOrderResult().getPackageValue());
                        WXPayUtils.WXPayBuilder builder = new WXPayUtils.WXPayBuilder();
                        builder.setAppId(date.getResult().getWxPayAppOrderResult().getAppId())
                                .setPartnerId(date.getResult().getWxPayAppOrderResult().getPartnerId())
                                .setPrepayId(date.getResult().getWxPayAppOrderResult().getPrepayId())
                                .setPackageValue(date.getResult().getWxPayAppOrderResult().getPackageValue())
                                .setNonceStr(date.getResult().getWxPayAppOrderResult().getNonceStr())
                                .setTimeStamp(date.getResult().getWxPayAppOrderResult().getTimeStamp())
                                .setSign(date.getResult().getWxPayAppOrderResult().getSign()).setAppId(UrlValuse.WXAPP_ID)
                                .build().toWXPayNotSign(PayActivity.this);
                    }
                }, new OkGoRequests.OnError<WXBean>() {
                    @Override
                    public void noData() {

                    }
                });
            }
        });

        ConnectivityManager conMann = (ConnectivityManager)
                this.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mobileNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifiNetworkInfo = conMann.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

        if (mobileNetworkInfo.isConnected()) {
            ip = getLocalIpAddress();
            System.out.println("本地ip-----" + ip);
        } else if (wifiNetworkInfo.isConnected()) {
            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            ip = intToIp(ipAddress);
            System.out.println("wifi_ip地址为------" + ip);
        }


        final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp("wxed61e43845c60a4d");

//        OkGo.<String>post("https://api.mch.weixin.qq.com/pay/closeorder").tag(this).upString().execute(new StringCallback() {
//            @Override
//            public void onSuccess(Response<String> response) {
//
//            }
//        });


//        LiteOrmTools.getInformation(RegisterBean.ResultBean.class, this, new LiteOrmTools.On<RegisterBean.ResultBean>() {
//            @Override
//            public void hasData(RegisterBean.ResultBean data) {
//                token = data.getC_token();
//            }
//        }, new LiteOrmTools.OFF() {
//            @Override
//            public void noData() {
//                tag = false;
//            }
//        });
//        if (tag) {
//            initQueryDateHtml(token);
//        }

    }

    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

    public String getLocalIpAddress() {
        try {
            ArrayList<NetworkInterface> nilist = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface ni : nilist) {
                ArrayList<InetAddress> ialist = Collections.list(ni.getInetAddresses());
                for (InetAddress address : ialist) {
                    if (!address.isLoopbackAddress() && address instanceof Inet4Address) {
                        return address.getHostAddress();
                    }
                }

            }

        } catch (SocketException ex) {
            Log.e("localip", ex.toString());
        }
        return null;
    }

    public static String intToIp(int ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0x001) {
            int a = data.getIntExtra("tag", 0);
//          Toast.makeText(this, "aaaaaaaa:" + a, Toast.LENGTH_SHORT).show();

        }
    }

//    private void startTime() {
//        timer = new CountDownTimer(5000, 1000) {
//            @Override
//            public void onTick(long millisUntilFinished) {
//                mTimeTv.setText((millisUntilFinished / 1000) + "s");
//            }
//
//            @Override
//            public void onFinish() {
//                Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
//                startActivity(intent);
//                finish();
//            }
//        }.start();
//
//
//    }
//
//    @Override
//    protected void onPause() {
//        super.onPause();
//        timer.cancel();
//    }
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        timer.cancel();
//    }
}
